package com.bigkoo.pickerviewdemo.slice;

import com.bigkoo.pickerview.Utils.ResUtil;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.*;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bigkoo.pickerview.view.TimePickerView;
import com.bigkoo.pickerviewdemo.ResourceTable;
import com.bigkoo.pickerviewdemo.bean.CardBean;
import com.bigkoo.pickerviewdemo.bean.ProvinceBean;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.agp.utils.Color;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.CommonDialog;
import ohos.agp.window.dialog.ToastDialog;
import ohos.agp.window.service.Window;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

public class MainAbilitySlice extends AbilitySlice implements Component.ClickedListener {

    private Button btn_circle, btn_time, btn_CustomTime;
    private Button btn_to_Fragment, btn_lunar_time, btn_Options;
    private Button btn_CustomOptions, btn_no_linkage, btn_OptionsJsonParse;
    private ArrayList<ProvinceBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();

    private TimePickerView pvTime, pvCustomTime, pvCustomLunar;
    private OptionsPickerView pvOptions, pvCustomOptions, pvNoLinkOptions;
    private ArrayList<CardBean> cardItem = new ArrayList<>();

    private ArrayList<String> food = new ArrayList<>();
    private ArrayList<String> clothes = new ArrayList<>();
    private ArrayList<String> computer = new ArrayList<>();

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        ComponentContainer rootLayout = (ComponentContainer)
                LayoutScatter.getInstance(getContext()).parse(ResourceTable.Layout_ability_main, null, false);
        super.setUIContent(rootLayout);

        //等数据加载完毕再初始化并显示Picker,以免还未加载完数据就显示,造成APP崩溃。
        getOptionData();
        initOptionPicker();
        initCustomOptionPicker();
        initNoLinkOptionsPicker();
        initTimePicker();
        initLunarPicker();
        initCustomTimePicker();

        btn_Options = ResUtil.findViewById(rootLayout, ResourceTable.Id_btn_Options);
        btn_CustomOptions = ResUtil.findViewById(rootLayout, ResourceTable.Id_btn_CustomOptions);
        btn_no_linkage = ResUtil.findViewById(rootLayout, ResourceTable.Id_btn_no_linkage);
        btn_OptionsJsonParse = ResUtil.findViewById(rootLayout, ResourceTable.Id_btn_GotoJsonData);
        btn_time = (Button) findComponentById(ResourceTable.Id_btn_time);
        btn_CustomTime = (Button) findComponentById(ResourceTable.Id_btn_CustomTime);
        btn_to_Fragment = (Button) findComponentById(ResourceTable.Id_btn_fragment);
        btn_lunar_time = (Button) findComponentById(ResourceTable.Id_btn_lunar_time);
        btn_circle = ResUtil.findViewById(rootLayout, ResourceTable.Id_btn_circle);

        btn_Options.setClickedListener(this);
        btn_CustomOptions.setClickedListener(this);
        btn_no_linkage.setClickedListener(this);
        btn_OptionsJsonParse.setClickedListener(this);
        btn_to_Fragment.setClickedListener(this);
        btn_CustomTime.setClickedListener(this);
        btn_time.setClickedListener(this);
        btn_circle.setClickedListener(this);
        btn_lunar_time.setClickedListener(this);
    }

    private void initOptionPicker() {//条件选择器初始化

        /**
         * 注意 ：如果是三级联动的数据(省市区等)，请参照 JsonDataActivity 类里面的写法。
         */
        pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, Component v) {
                //返回的分别是三个级别的选中位置
                String tx = options1Items.get(options1).getPickerViewText()
                        + options2Items.get(options1).get(options2)
                        /* + options3Items.get(options1).get(options2).get(options3).getPickerViewText()*/;
                btn_Options.setText(tx);
            }
        })
                .setTitleText("城市选择")
                .setContentTextSize(20)//设置滚轮文字大小
                .setDividerColor(Color.LTGRAY.getValue())//设置分割线的颜色
                .setSelectOptions(0, 1)//默认选中项
                .setBgColor(Color.BLACK.getValue())
                .setTitleBgColor(Color.DKGRAY.getValue())
                .setTitleColor(Color.LTGRAY.getValue())
                .setCancelColor(Color.YELLOW.getValue())
                .setSubmitColor(Color.YELLOW.getValue())
                .setTextColorCenter(Color.LTGRAY.getValue())
                .setTextColorOut(Color.WHITE.getValue())
                .isRestoreItem(true)//切换时是否还原，设置默认选中第一项。
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setLabels("省", "市", "区")
                .setOutSideColor(0x00000000) //设置外部遮罩颜色
                .setOptionsSelectChangeListener(new OnOptionsSelectChangeListener() {
                    @Override
                    public void onOptionsSelectChanged(int options1, int options2, int options3) {
                        String str = "options1: " + options1 + "\noptions2: " + options2 + "\noptions3: " + options3;
                        ResUtil.displayToast(getContext(), str);
                    }
                })
                .isDialog(true)
                .build();


        pvOptions.setPicker(options1Items, options2Items);//二级选择器
    }

    private void initCustomOptionPicker() {//条件选择器初始化，自定义布局
        /**
         * @description
         *
         * 注意事项：
         * 自定义布局中，id为 optionspicker 或者 timepicker 的布局以及其子控件必须要有，否则会报空指针。
         * 具体可参考demo 里面的两个自定义layout布局。
         */
        pvCustomOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, Component v) {
                //返回的分别是三个级别的选中位置
                String tx = cardItem.get(options1).getPickerViewText();
                btn_CustomOptions.setText(tx);
            }
        })
                .setLayoutRes(ResourceTable.Layout_pickerview_custom_options, new CustomListener() {
                    @Override
                    public void customLayout(Component v) {
                        final Text tvSubmit = (Text) v.findComponentById(ResourceTable.Id_tv_finish);
                        final Text tvAdd = (Text) v.findComponentById(ResourceTable.Id_tv_add);
                        Image ivCancel = (Image) v.findComponentById(ResourceTable.Id_iv_cancel);
                        tvSubmit.setClickedListener(new Component.ClickedListener() {
                            @Override
                            public void onClick(Component component) {
                                pvCustomOptions.returnData();
                                pvCustomOptions.dismiss();
                            }
                        });

                        ivCancel.setClickedListener(new Component.ClickedListener() {
                            @Override
                            public void onClick(Component v) {
                                pvCustomOptions.dismiss();
                            }
                        });

                        tvAdd.setClickedListener(new Component.ClickedListener() {
                            @Override
                            public void onClick(Component v) {
                                getCardData();
                                pvCustomOptions.setPicker(cardItem);
                            }
                        });

                    }
                })
                .isDialog(false)
                .setOutSideCancelable(false)
                .build();
        pvCustomOptions.setPicker(cardItem);//添加数据


    }

    private void initNoLinkOptionsPicker() {// 不联动的多级选项
        pvNoLinkOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {

            @Override
            public void onOptionsSelect(int options1, int options2, int options3, Component v) {

                String str = "food:" + food.get(options1)
                        + "\nclothes:" + clothes.get(options2)
                        + "\ncomputer:" + computer.get(options3);

                ResUtil.displayToast(getContext(), str);
            }
        })
                .setOptionsSelectChangeListener(new OnOptionsSelectChangeListener() {
                    @Override
                    public void onOptionsSelectChanged(int options1, int options2, int options3) {
                        String str = "options1: " + options1 + "\noptions2: " + options2 + "\noptions3: " + options3;
                        ResUtil.displayToast(getContext(), str);
                    }
                })
                .setItemVisibleCount(5)
                .isDialog(false)
                // .setSelectOptions(0, 1, 1)
                .build();
        pvNoLinkOptions.setNPicker(food, clothes, computer);
        pvNoLinkOptions.setSelectOptions(0, 1, 1);


    }

    private void initCustomTimePicker() {
        Calendar selectedDate = Calendar.getInstance();
        Calendar startDate = Calendar.getInstance();
        startDate.set(2014, 1, 23);
        Calendar endDate = Calendar.getInstance();
        endDate.set(2027, 2, 28);
        pvCustomTime = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, Component v) {
                btn_CustomTime.setText(getTime(date));
            }
        }).setDate(selectedDate)
                .setRangDate(startDate, endDate)
                .setLayoutRes(ResourceTable.Layout_pickerview_custom_time, new CustomListener() {
                    @Override
                    public void customLayout(Component v) {
                        final Text tvSubmit = (Text) v.findComponentById(ResourceTable.Id_tv_finish);
                        Image ivCancel = (Image) v.findComponentById(ResourceTable.Id_iv_cancel);
                        tvSubmit.setClickedListener(new Component.ClickedListener() {
                            @Override
                            public void onClick(Component component) {
                                pvCustomTime.returnData();
                                pvCustomTime.dismiss();
                            }
                        });
                        ivCancel.setClickedListener(new Component.ClickedListener() {
                            @Override
                            public void onClick(Component component) {
                                pvCustomTime.dismiss();

                            }
                        });
                    }
                }).setContentTextSize(18)
                .setType(new boolean[]{false, false, false, true, true, true})
                .setLabel("年", "月", "日", "时", "分", "秒")
                .setLineSpacingMultiplier(1.2f)
                .setTextXOffset(0, 0, 0, 40, 0, -40)
                .isCenterLabel(false)
                .setDividerColor(0xFF24AD9D)
                .isDialog(false)
                .build();
    }

    private String getTime(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return format.format(date);
    }

    private void initTimePicker() {
        pvTime = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, Component v) {
                ToastDialog toast = new ToastDialog(getContext());
                toast.setText(getTime(date));
                toast.setSize(800, 200);
                toast.setOffset(50, 600);
                toast.show();
            }
        }).setTimeSelectChangeListener(new OnTimeSelectChangeListener() {
            @Override
            public void onTimeSelectChanged(Date date) {

            }
        }).setType(new boolean[]{true, true, true, true, true, true})
                .isDialog(false)
                .addOnCancelClickListener(new Component.ClickedListener() {
                    @Override
                    public void onClick(Component component) {

                    }
                }).setItemVisibleCount(5)
                .setLineSpacingMultiplier(2.0f)
                .isAlphaGradient(true)
                .build();

        CommonDialog mDialog = pvTime.getDialog();

        if (mDialog != null) {

            StackLayout.LayoutConfig params = new StackLayout.LayoutConfig(
                    ComponentContainer.LayoutConfig.MATCH_PARENT,
                    ComponentContainer.LayoutConfig.MATCH_CONTENT,
                    LayoutAlignment.BOTTOM);

            params.setMarginLeft(0);
            params.setMarginRight(0);
            params.height = 500;

            pvTime.getDialogContainerLayout().setLayoutConfig(params);

            Window dialogWindow = mDialog.getWindow();
            if (dialogWindow != null) {
                dialogWindow.setLayoutAlignment(LayoutAlignment.BOTTOM);
                dialogWindow.setTransparent(true);
            }
        }
    }

    private void initLunarPicker() {
        Calendar selectedDate = Calendar.getInstance();
        Calendar startDate = Calendar.getInstance();
        startDate.set(2014, 1, 23);
        Calendar endDate = Calendar.getInstance();
        endDate.set(2069, 2, 28);


        pvCustomLunar = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, Component v) {

            }
        }).setDate(selectedDate)
                .setRangDate(startDate, endDate)
                .setLayoutRes(ResourceTable.Layout_pickerview_custom_lunar, new CustomListener() {

                    @Override
                    public void customLayout(final Component v) {

                        final Text tvSubmit = (Text) v.findComponentById(ResourceTable.Id_tv_finish);
                        Image ivCancel = (Image) v.findComponentById(ResourceTable.Id_iv_cancel);
                        tvSubmit.setClickedListener(new Component.ClickedListener() {
                            @Override
                            public void onClick(Component component) {
                                pvCustomLunar.returnData();
                                pvCustomLunar.dismiss();
                            }
                        });

                        ivCancel.setClickedListener(new Component.ClickedListener() {
                            @Override
                            public void onClick(Component component) {
                                pvCustomLunar.dismiss();

                            }
                        });

                        Checkbox cb_lunar = (Checkbox) v.findComponentById(ResourceTable.Id_cb_lunar);
                        cb_lunar.setCheckedStateChangedListener(new AbsButton.CheckedStateChangedListener() {
                            @Override
                            public void onCheckedChanged(AbsButton absButton, boolean b) {
                                pvCustomLunar.setLunarCalendar(!pvCustomLunar.isLunarCalendar());
                                setTimePickerChildWeight(v, b ? 0.8f : 1f, b ? 1f : 1.1f);
                            }
                        });

                    }

                    private void setTimePickerChildWeight(Component v, float yearWeight, float weight) {
                        ComponentContainer timePicker = (ComponentContainer) v.findComponentById(ResourceTable.Id_timepicker);
                        Component year = timePicker.getComponentAt(0);
                        DirectionalLayout.LayoutConfig lp = ((DirectionalLayout.LayoutConfig) year.getLayoutConfig());
                        lp.weight = yearWeight;
                        year.setLayoutConfig(lp);
                        for (int i = 1; i < timePicker.getChildCount(); i++) {
                            Component childAt = timePicker.getComponentAt(i);
                            DirectionalLayout.LayoutConfig childLp = ((DirectionalLayout.LayoutConfig) childAt.getLayoutConfig());
                            childLp.weight = weight;
                            childAt.setLayoutConfig(childLp);
                        }
                    }


                })
                .setType(new boolean[]{true, true, true, false, false, false})
                .isCenterLabel(false) //Indicates whether to display only the label text of the selected item in the middle. The value false indicates that all items contain labels.
                .setDividerColor(Color.RED.getValue())
                .isDialog(true)
                .build();


    }


    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    public void onClick(Component component) {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ABILITY_NEW_MISSION);
        switch (component.getId()) {
            case ResourceTable.Id_btn_circle:
                present(new WheelViewAbilitySlice(), intent);
                break;
            case ResourceTable.Id_btn_Options:
                if (pvOptions != null) {
                    pvOptions.show(); //弹出条件选择器
                }
                break;
            case ResourceTable.Id_btn_CustomOptions:
                if (pvCustomOptions != null) {
                    pvCustomOptions.show(); //弹出自定义条件选择器
                }
                break;
            case ResourceTable.Id_btn_no_linkage:
                if (pvNoLinkOptions != null) {
                    pvNoLinkOptions.show();
                }
                break;
            case ResourceTable.Id_btn_GotoJsonData:
                present(new JsonDataAbilitySlice(), intent);
                break;
            case ResourceTable.Id_btn_time:
                pvTime.show(component);
                break;

            case ResourceTable.Id_btn_lunar_time:
                pvCustomLunar.show();
                break;

            case ResourceTable.Id_btn_CustomTime:
                pvCustomTime.show();
                break;
            case ResourceTable.Id_btn_fragment:
                Intent in = new Intent();
                in.addFlags(Intent.FLAG_ABILITY_NEW_MISSION);
                present(new TestAbilityslice(), in);
                break;
            default:
                break;
        }
    }

    private void getOptionData() {
        /*
         * 注意：如果是添加JavaBean实体数据，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        getCardData();
        getNoLinkData();

        //选项1
        options1Items.add(new ProvinceBean(0, "广东", "描述部分", "其他数据"));
        options1Items.add(new ProvinceBean(1, "湖南", "描述部分", "其他数据"));
        options1Items.add(new ProvinceBean(2, "广西", "描述部分", "其他数据"));

        //选项2
        ArrayList<String> options2Items_01 = new ArrayList<>();
        options2Items_01.add("广州");
        options2Items_01.add("佛山");
        options2Items_01.add("东莞");
        options2Items_01.add("珠海");
        ArrayList<String> options2Items_02 = new ArrayList<>();
        options2Items_02.add("长沙");
        options2Items_02.add("岳阳");
        options2Items_02.add("株洲");
        options2Items_02.add("衡阳");
        ArrayList<String> options2Items_03 = new ArrayList<>();
        options2Items_03.add("桂林");
        options2Items_03.add("玉林");
        options2Items.add(options2Items_01);
        options2Items.add(options2Items_02);
        options2Items.add(options2Items_03);
        /*--------数据源添加完毕---------*/
    }

    private void getCardData() {
        for (int i = 0; i < 5; i++) {
            cardItem.add(new CardBean(i, "No.ABC12345 " + i));
        }

        for (int i = 0; i < cardItem.size(); i++) {
            if (cardItem.get(i).getCardNo().length() > 6) {
                String str_item = cardItem.get(i).getCardNo().substring(0, 6) + "...";
                cardItem.get(i).setCardNo(str_item);
            }
        }
    }

    private void getNoLinkData() {
        food.add("KFC");
        food.add("MacDonald");
        food.add("Pizza hut");

        clothes.add("Nike");
        clothes.add("Adidas");
        clothes.add("Armani");
        computer.add("ASUS");
        computer.add("Lenovo");
        computer.add("Apple");
        computer.add("HP");
    }
}
